<template>
  <div class="table-container">
    <el-table
      :data="tableData"
      :span-method="objectSpanMethod"
      border
      style="width: 100%">
      <el-table-column prop="name" label="姓名" align="center"></el-table-column>
      <el-table-column prop="age" label="年龄" align="center"></el-table-column>
      <el-table-column prop="address" label="地址" align="center"></el-table-column>
      <el-table-column prop="department" label="部门" align="center"></el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { name: '张三', age: 20, address: '北京市', department: '技术部' },
        { name: '李四', age: 20, address: '北京市', department: '技术部' },
        { name: '王五', age: 22, address: '上海市', department: '市场部' },
        { name: '赵六', age: 22, address: '上海市', department: '市场部' },
        { name: '钱七', age: 22, address: '上海市', department: '市场部' },
        { name: '孙八', age: 25, address: '广州市', department: '财务部' }
      ],
      // 存储各列合并信息的对象
      spanArr: {
        name: [],
        age: [],
        address: [],
        department: []
      },
      // 存储各列合并计数的对象
      position: {
        name: 0,
        age: 0,
        address: 0,
        department: 0
      }
    }
  },
  created() {
    // 初始化时处理合并逻辑
    this.handleMergeColumns(['name', 'age', 'address', 'department']);
  },
  methods: {
    // 处理需要合并的列
    handleMergeColumns(columns) {
      columns.forEach(column => {
        this.spanArr[column] = [];
        this.position[column] = 0;
        
        // 遍历数据，构建合并信息
        for (let i = 0; i < this.tableData.length; i++) {
          if (i === 0) {
            this.spanArr[column].push(1);
            this.position[column] = 0;
          } else {
            // 判断当前单元格内容与上一行是否相同
            if (this.tableData[i][column] === this.tableData[i - 1][column]) {
              this.spanArr[column][this.position[column]] += 1;
              this.spanArr[column].push(0);
            } else {
              this.spanArr[column].push(1);
              this.position[column] = i;
            }
          }
        }
      });
    },
    // 表格单元格合并方法
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const columnKey = column.property;
      
      // 检查该列是否需要合并
      if (this.spanArr[columnKey] && this.spanArr[columnKey][rowIndex]) {
        return {
          rowspan: this.spanArr[columnKey][rowIndex],
          colspan: 1
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0
        };
      }
    }
  }
}
</script>

<style scoped>
.table-container {
  padding: 20px;
}
</style>    